import { Base64 } from 'js-base64';
//
class auth {
    person = {
        username: null,
        password: null,
        authorName: null,
        headUrl: null,
        gender: null,
        role: null
    }

    //保存token令牌
    saveToken(token) {
            localStorage.setItem("loginToken", token);
            //读取载荷信息，分割JWT令牌
            let strArray = token.split(".");
            //获取载荷部分
            let payload = strArray[1];
            //吧编码转换成json对象，因为包含了当前登录人的信息
            //Buffer是node。js中的语法，wedpack会处理node.js的语法。放心用
            let authorInfo = Base64.decode(payload);
            console.log(authorInfo);
            //保存登录信息
            localStorage.setItem("loginUser", authorInfo);

        }
        //获取登录人的信息
    getLoginUser() {
            let jsonStr = localStorage.getItem("loginUser");
            if (jsonStr == null || jsonStr == undefined) {
                return this.person;
            } else {
                this.person = JSON.parse(jsonStr);
            }
            return this.person;
        }
        //更新登录人的信息
    updateLoginUser(authorInfo) {
            //将传进来的JSON对象转换成字符串
            let jsonStr = JSON.stringify(authorInfo);
            localStorage.setItem("loginUser", jsonStr); //!!!!
        }
        //读取令牌
    getToken() {
        let token = localStorage.getItem("loginToken");
        return token;
    }

    //判断登录状态
    isLogin() {
            let token = localStorage.getItem("loginToken");
            if (token == undefined || token == null) {
                return false;
            } else {
                return true;
            }
        }
        //登出，删除登录人信息即可
    logout() {
        localStorage.removeItem("loginToken");
        localStorage.removeItem("loginUser");
    }
    getRole() {
        return this.getLoginUser().role
    }
}
//实例化auth对象
const authInstance = new auth();

export default authInstance;